package de.lp.jsontest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;

public class ServerAccess_GPS_Alarm extends Activity {
	
	private int userID;
	private final String serverAdress = "http://10.0.2.2:3000/";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_json);
		userID = -1;
	
		try {
			//register("Zauberer@d3.net", "Arkankraft");
			login("moench@d3.net", "geisteskraft");
			loadPOIs();
			
			logout();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	public void login(String user, String pw) throws JSONException {
		
		int login = -1;
		login = findUser(user, pw, true);
		
		if (login == -1) {
			System.out.println("login request failed/no connection!");
		} else if (login == 0) {
			System.out.println("user name or password incorrect!");
		} else {
			System.out.println("password correct, login successful!");
			userID = login;
		}
	}
	
	public void logout() {
		userID = -1;
		
		System.out.println("logout successful!");
	}
	
	public void register(String user, String pw) throws JSONException, ClientProtocolException, IOException {
		JSONObject data = new JSONObject();
		
		if (findUser(user, pw, false) == 1) {
			System.out.println("User already exists!");
		}
		
		data.put("utf8", "V");		
		data.put("authenticity_token", "h3f1svg/XvyxrC7Be4yiC1nD90Y1YM47WUpLVx1fiF0=");
		JSONObject userData = new JSONObject();
		userData.put("Email", user);
		userData.put("Password", pw);
		data.put("user", userData);
		data.put("commit", "Create User");
		
		StringEntity se = new StringEntity(data.toString());
		
		if (httpPost(se, serverAdress + "users.json")) {
			System.out.println("registered successfully!");
		} else {
			System.out.println("failed to register");
		}
	}
	
	/*
	 * searches for User 'user'. If no PW-check was requested 
	 * 			it either returns 1 if user exists 
	 * 			or 0 if not.
	 * If PW-check was requested, it returns 
	 * 			the id of the user if he exists and the PW is correct,
	 * 			0 if PW or user name is not correct
	 * -1 if the request failed
	 */
	private int findUser(String user, String pw, boolean checkPW) throws JSONException {
		JSONArray jsonArray = httpGetMultiple(serverAdress + "users.json");
		
		if (jsonArray == null) {
			System.out.println("request failed!");
			return -1;
		}
		
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject;
			jsonObject = jsonArray.getJSONObject(i);
			
			if (jsonObject.getString("Email").equals(user)) {
				if (!checkPW) {
					return 1;
				}
				if (jsonObject.getString("Password").equals(pw)) {					
					return jsonObject.getInt("id");
				} else {
					return 0;
				}
			}
		}
		return 0;
		
	}
	
	public void loadPOIs() throws JSONException {
		
		if (this.userID == -1) {
			System.out.println("Please login or register first.");
			return;
		}
		JSONArray allPois = httpGetMultiple(serverAdress + "pois.json");
		if (allPois == null) {
			System.out.println("could not load POIs");
			return;
		}
		JSONArray pois = new JSONArray();
		
		for (int i = 0; i < allPois.length(); i++) {
			
			if (allPois.getJSONObject(i).getInt("user_id") == this.userID) {
				pois.put(allPois.getJSONObject(i));
			}				
		}
		
		for (int i=0; i<pois.length(); i++) {
			System.out.println(pois.getJSONObject(i).toString());
		}
			
	}
	
	public boolean savePoi (double radius, double x, double y, String description) throws JSONException, ClientProtocolException, IOException {
		//{"utf8"=>"V", "authenticity_token"=>"h3f1svg/XvyxrC7Be4yiC1nD90Y1YM47WUpLVx1fiF0=", "poi"=>{"Radius"=>"3,14", "XCoordinate"=>"24.9", "YCoordinate"=>"0.76", 
		//"Description"=>"where is that?", "user_id"=>"3"}, "commit"=>"Create Poi"}
		if (userID == -1) {
			System.out.println("You have to register or login first");
			return false;
		}
		
		JSONObject data = new JSONObject();
		
		data.put("utf8", "V");		
		data.put("authenticity_token", "h3f1svg/XvyxrC7Be4yiC1nD90Y1YM47WUpLVx1fiF0=");
		JSONObject poiData = new JSONObject();
		poiData.put("Radius", radius);
		poiData.put("XCoordinate", x);
		poiData.put("YCoordinate", y);
		poiData.put("Description", description);
		poiData.put("user_id", this.userID);
		data.put("poi", poiData);
		data.put("commit", "Create Poi");
		
		StringEntity se = new StringEntity(data.toString());
		
		if (httpPost(se, serverAdress + "pois.json")) {
			System.out.println("POI saved successfully!");
			return true;
		} else {
			System.out.println("failed to save POI");
			return false;
		}
	}

	private boolean httpPost(StringEntity message, String path) throws ClientProtocolException, IOException {
		// prepare JSONObject
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(path);
		// senden
		httpPost.setEntity(message);
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-type", "application/json");
		
		HttpResponse response = httpclient.execute(httpPost);
		int code = response.getStatusLine().getStatusCode();
		//System.out.println(code);
		
		if (code == 201) {
			//System.out.println("POST was successful!");
			return true;
		} else {
			//System.out.println("POST failed!");
			return false;
		}

	}

	private JSONArray httpGetMultiple(String path) {
		try {
			String readJson = httpGet(path);
			JSONArray jsonArray = new JSONArray(readJson);
			return jsonArray;
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private JSONObject httpGetSingle(String path) {
		try {
			String readJson = httpGet(path);
			JSONObject jsonObject = new JSONObject(readJson);
			return jsonObject;
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	private String httpGet(String path) throws ClientProtocolException, IOException {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(path);
		
		HttpResponse response = client.execute(httpGet);
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		if (statusCode == 200) {
			HttpEntity entity = response.getEntity();
			InputStream content = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			return builder.toString();
		} else {
			System.out.println("Failed to download file");
			return "";
		}
	}

    
}
